#!/usr/bin/env python
# -*- coding: utf-8 -*-

#-*-
# UbiNote - A Lightweight Note-talking Application
#
# Copyright (C) 2006-2009 Shellex <5h3ll3x@gmail.com>
#
# UbiNote is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# UbiNote is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with UbiNote; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA


from notemgr import notemgr
from blockmgr import blockmgr
from tagmgr import tagmgr
import json
def dumps(state, data=''):
    return json.dumps([state, data])

def save_block_tag(request, block_id, tags):
    new_tagname_set = None
    try:
        if not block_id.isdigit():
            raise TypeError, 'block_id(%s) is not a digit' % id
        new_tagname_set = set(
            filter(lambda x: len(x)!=0, 
                [e.strip() for e in json.loads(tags)]))
    except TypeError, e:
        request.respond(s.dumps(500, repr(e)))
        request.done(500)
        return

    old_tags = [t for t in tagmgr.get_from_block(block_id)]
    old_tagname_set = set([t.name for t in old_tags])
    attach_set = new_tagname_set.difference(old_tagname_set)
    detach_set = old_tagname_set.difference(new_tagname_set)
    print attach_set, detach_set
    id = -1
    for e in attach_set:
        existed_tag = tagmgr.get_by_name(e)
        if (existed_tag.id == -1):
            id = tagmgr.add(e) 
        else:
            id = existed_tag.id
        tagmgr.attach(id, block_id)
    for e in detach_set:
        t = filter(lambda x:x.name == e, [t for t in old_tags])
        tagmgr.detach(t[0].id, block_id)
    request.respond(dumps(200, {'block_id':block_id}))
    request.done(200)

def list_block_tag(request, block_id):
    try:
        if not block_id.isdigit():
            raise TypeError, 'block_id(%s) is not a digit' % id
    except TypeError, e:
        request.respond(dumps(500, repr(e)))
        request.done(500)
    ts = [t.serialize() for t in tagmgr.get_from_block(block_id)]
    request.respond(dumps(200, {'block_id':block_id, 'tags':ts}))
    request.done(200)

def list_tag(request, count=-1):
    ts =[]
    if count == -1:
        ts = [t.serialize() for t in tagmgr.get_all()]
    else:
        ts = [t.serialize() for t in tagmgr.get_popular(count)]
    ts.sort(key=lambda x: x['count'], reverse = True)
    request.respond(dumps(200, ts))
    request.done(200)

